package com.cyt.web.controller.sys;

import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.BaseUtil;
import com.cyt.base.util.ErrorCode;
import com.cyt.sys.model.po.SysJob;
import com.cyt.sys.model.vo.SysJobVo;
import com.cyt.sys.service.SysJobService;
import com.cyt.sys.util.SchedulerUtils;
import com.github.pagehelper.StringUtil;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;

/**
 * 定时任务
 *
 * @author congcong tao
 * @date 2018/11/26 14:36
 */
@RestController
@RequestMapping("/baseJob")
public class SysJobController extends SysBaseController {

    private static Logger log = LoggerFactory.getLogger(SysJobController.class);
    @Resource
    private Scheduler scheduler;
    @Resource
    private SysJobService sysJobService;
    private SysJob sysJob;

    /**
     * 分页页面
     *
     * @author congcong tao
     * @date 2019/2/27 11:29
     */
    @RequestMapping("/listPage")
    public ModelAndView listPage() {
        return new ModelAndView("/sys/job/baseJobList");
    }

    /**
     * 分页数据json返回值
     *
     * @param sysJobVo 查询参数
     * @param limit    页面大小
     * @param page     当前页面
     * @author congcong tao
     * @date 2019/2/27 11:30
     */
    @RequestMapping(value = "/jsonList", method = RequestMethod.POST)
    public ReturnResult jsonList(SysJobVo sysJobVo, int limit, int page) throws MalformedURLException, UnsupportedEncodingException {
        ReturnResult returnResult = sysJobService.page(sysJobVo, limit, page);
        return returnResult;
    }

    /**
     * 表单详情页面
     *
     * @param id 主键
     * @author congcong tao
     * @date 2019/2/27 11:31
     */
    @RequestMapping(value = "/selectEntity", method = RequestMethod.GET)
    public ModelAndView selectEntity(String id) {
        ModelAndView view = new ModelAndView("/baseJobUpdateOrSave");
        sysJob = sysJobService.selectByPrimaryKey(id);
        view.addObject("baseJob", sysJob);
        return view;
    }

    /**
     * 更新or保存
     *
     * @param sysJobvo 表单数据
     * @author congcong tao
     * @date 2019/2/27 11:31
     */
    @RequestMapping(value = "/updateOrAddEntity", method = RequestMethod.POST)
    public ReturnResult updateOrAddEntity(SysJobVo sysJobvo) {
        if (StringUtil.isEmpty(sysJobvo.getId())) {
            sysJob = new SysJob();
            sysJob.setId(BaseUtil.uId());
            sysJob.setJobName(sysJobvo.getJobName());
            sysJob.setJobGroup(sysJobvo.getJobGroup());
            sysJob.setClassName(sysJobvo.getClassName());
            sysJob.setCronExpression(sysJobvo.getCronExpression());
            sysJob.setStatus(BaseConstant.SchedulerStatus.NORMAL.getValue());
            int id = sysJobService.insert(sysJob);
            if (id <= 0) {
                return new ReturnResult(ErrorCode.CODE_100, BaseConstant.DATABASE_ERROR_INSERT);
            } else {
                SchedulerUtils.createScheduleJob(sysJob, scheduler);
            }
        } else {
            sysJob = sysJobService.selectByPrimaryKey(sysJobvo.getId());
            sysJob.setJobName(sysJobvo.getJobName());
            sysJob.setJobGroup(sysJobvo.getJobGroup());
            sysJob.setClassName(sysJobvo.getClassName());
            sysJob.setCronExpression(sysJobvo.getCronExpression());
            int id = sysJobService.updateByPrimaryKeySelective(sysJob);
            if (id <= 0) {
                return new ReturnResult(ErrorCode.CODE_100, BaseConstant.DATABASE_ERROR_INSERT);
            } else {
                SchedulerUtils.updateScheduleJob(scheduler, sysJob);
            }
        }
        return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
    }

    /**
     * 开启定时任务
     *
     * @param id 主键
     * @author congcong tao
     * @date 2019/2/27 11:31
     */
    @RequestMapping(value = "/resumeJob", method = RequestMethod.GET)
    public ReturnResult resumeJob(String id) {
        if (StringUtil.isEmpty(id)) {
            return new ReturnResult(ErrorCode.CODE_200, BaseConstant.DATABASE_ERROR_UPDATE);
        } else {
            sysJob = sysJobService.selectByPrimaryKey(id);
            sysJob.setStatus(BaseConstant.SchedulerStatus.NORMAL.getValue());
            int info = sysJobService.updateByPrimaryKey(sysJob);
            if (info <= 0) {
                return new ReturnResult(ErrorCode.CODE_200, BaseConstant.DATABASE_ERROR_UPDATE);
            } else {
                SchedulerUtils.resumeJob(scheduler, sysJob.getJobName(), sysJob.getJobGroup());
            }
        }
        return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
    }

    /**
     * 暂停定时任务
     *
     * @param id 主键
     * @author congcong tao
     * @date 2019/2/27 11:31
     */
    @RequestMapping(value = "/pauseJob", method = RequestMethod.GET)
    public ReturnResult pauseJob(String id) {
        if (StringUtil.isEmpty(id)) {
            return new ReturnResult(ErrorCode.CODE_200, BaseConstant.DATABASE_ERROR_UPDATE);
        } else {
            sysJob = sysJobService.selectByPrimaryKey(id);
            sysJob.setStatus(BaseConstant.SchedulerStatus.PAUSE.getValue());
            int info = sysJobService.updateByPrimaryKey(sysJob);
            if (info <= 0) {
                return new ReturnResult(ErrorCode.CODE_200, BaseConstant.DATABASE_ERROR_UPDATE);
            } else {
                SchedulerUtils.pauseJob(scheduler, sysJob.getJobName(), sysJob.getJobGroup());
            }
        }
        return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
    }

    /**
     * 执行一次定时任务
     *
     * @param id 主键
     * @author congcong tao
     * @date 2019/2/27 11:31
     */
    @RequestMapping(value = "/run", method = RequestMethod.GET)
    public ReturnResult run(String id) {
        if (StringUtil.isEmpty(id)) {
            return new ReturnResult(ErrorCode.CODE_200, BaseConstant.DATABASE_ERROR_UPDATE);
        } else {
            SysJob jobRecord = sysJobService.selectByPrimaryKey(id);
            SchedulerUtils.runOne(scheduler, jobRecord);
        }
        return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
    }

    /**
     * 删除定时任务
     *
     * @param id 主键
     * @author congcong tao
     * @date 2019/2/27 11:31
     */
    @RequestMapping(value = "/deleteEntity", method = RequestMethod.GET)
    public ReturnResult deleteEntity(String id) {
        if (StringUtil.isEmpty(id)) {
            return new ReturnResult(ErrorCode.CODE_200, BaseConstant.DATABASE_ERROR_UPDATE);
        } else {
            int ids = sysJobService.deleteByPrimaryKey(id);
            if (ids <= 0) {
                return new ReturnResult(ErrorCode.CODE_200, BaseConstant.DATABASE_ERROR_UPDATE);
            } else {
                SysJob jobRecord = sysJobService.selectByPrimaryKey(id);
                SchedulerUtils.deleteJob(scheduler, jobRecord.getJobName(), jobRecord.getJobGroup());
            }
        }
        return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
    }
}
